package com.oocl.producer.producer;

import java.util.Date;

import javax.jms.JMSException;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.oocl.producer.pojo.Book;

/**
 * SAX Handler
 * @author GANAB
 *
 */
public class BookHandler extends DefaultHandler{
	private BookProducer producer = null;
	private Book book;
	private String value;
	@Override
	public void startDocument() throws SAXException {
		System.out.println("Doc start and producer init.");
		producer = new BookProducer("BookQueue");
	}
	
	@Override
	public void endDocument() throws SAXException {
		System.out.println("Doc end and close producer.");
		try {
			producer.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if("book".equals(qName)){
			book = new Book();
		}	
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if("book".equals(qName)){
			//处理这个book.转JSON存入MQ
			try {
				producer.sendMsg(book.toJson());
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		if("name".equals(qName)){
			book.setName(value);
		}
		if("pubDate".equals(qName)){
			book.setPubDate(new Date(Long.parseLong(value)));
		}
		if("author".equals(qName)){
			book.setAuthor(value);
		}
		if("price".equals(qName)){
			book.setPrice(Double.parseDouble(value));
		}
		if("isNew".equals(qName)){
			book.setIsNew(value);
		}
		if("publisher".equals(qName)){
			book.setPublisher(value);
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		value = new String(ch,start,length);
	}

}
